package org.pupil.sort.bubbleSort;

import org.pupil.sort.ISort;

/**
 * @Description: 冒泡排序
 * @Author: pupil
 * @Date: 2024/07/31 下午 3:35
 */
public class BubbleSort {

    public static void bubbleSort(int[] arr) {
        if (arr == null || arr.length < 2) {
            return;
        }
        /**
         * 0 ~ n-1
         * 0 ~ n-2
         * 0 ~ n-3
         * 0 ~ end--
         * 0 ~ 0
         */
        for (int end = arr.length - 1; end > 0; end--) {
            /**
             * 0 ~ end
             * 0 1  i == 0 1
             * 1 2  i == 1 2
             * 2 3  i == 2 3
             * 3 4  i == 3 4
             * 4 5  i == 4 5
             * end-1 end
             */
            for (int i = 0; i < end; i++) {
                if (arr[i] > arr[i + 1]) {
                    ISort.swap(arr, i, i + 1);
                }
            }
        }
    }

    public static void main(String[] args) {
        int[] arr = new int[]{5, 3, 4, 1, 2};
        String print1 = ISort.print(arr);
        System.out.println("排序前：" + print1);
        bubbleSort(arr);
        String print2 = ISort.print(arr);
        System.out.println("排序后：" + print2);
    }
}
